#from django.views.decorators.csrf import csrf_exempt
# -*- coding: UTF-8 -*-
from soaplib_handler import DjangoSoapApp, soapmethod, soap_types
from PidaRestauranteWeb.nucleo.models import Funcionario
from PidaRestauranteWeb.web_service.models import Mesa
from PidaRestauranteWeb.vendas.models import *

from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.db import transaction
from django.shortcuts import render_to_response, get_object_or_404
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login as django_login, logout as django_logout
from django.contrib.messages import info, error
from django.template import RequestContext
from django.views.generic.create_update import update_object
from django.views.generic.list_detail import object_list
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django.core.files import File
from django.utils.html import *
from django.utils.safestring import mark_safe
from datetime import date, datetime


def finalizar_pedido(request, object_id):
    if request.method == 'POST':
        mesa = Mesa.objects.get(id=object_id)
        return HttpResponse(mesa)
    try:
        mesa = Mesa.objects.get(id=object_id)
        mesa.pedido
    except:
        return HttpResponse('erro')
    else:
        return render_to_response('nota_fiscal.html',{'mesa':mesa,'link':'web_service/mesa'}, context_instance=RequestContext(request))
    
    
################################### WEBSERVICE ########################################


def mesa_list(request, page):
    query_set = Mesa.objects.filter(em_aberto=True)
    return object_list(
                       request = request,
                       queryset = query_set,
                       paginate_by = 15,
                       page = page,
                       template_name = 'generic_list.html',
                       extra_context = {'title':u'Lista de mesas ocupadas',
                                        'link':'web_service/mesa',
                                        }
                       )

def objectsToString(objects, attr, separator, complete = ''):
        string = ""
        for object in objects:
            string += complete + str(object.__getattribute__(attr)) + separator
        return string[:-len(separator)]

    
def objectsToStringForItens(itens, attr, separator):
        string = ""
        for item in itens:
            string += str(item.id) + '-' + str(item.nome) + '-' + str(item.categoria) + '-' + str(item.preco) + '-' + str(item.quantidade) + '-' + str(item.descricao) + separator
        return string[:-len(separator)]

class AndroidService(DjangoSoapApp):

    __tns__ = 'http://localhost:8000/'

#    @soapmethod(soap_types.String, soap_types.Integer, _returns=soap_types.Array(soap_types.String))
#    def say_hello(self, name, times):
#        results = []
#        for i in range(0, times):
#            results.append('Hello, %s'%name)
#        return results

    @soapmethod(soap_types.String, _returns=soap_types.String)
    def ping(self, ping):
        ping += ping + "/Server"
        return ping

    @soapmethod(soap_types.String, soap_types.String, _returns=soap_types.String)
    def efetuarLogin(self, username, password):
        user = authenticate(username=username, password=password)
        try:
            #if(user.funcionario.is_garcom()):
            if user is not None:
                return str(user.funcionario.id)
        except:
            pass
        return "None"
    
    @soapmethod(soap_types.String, soap_types.String, _returns=soap_types.String)
    def getItens(self, categoria, separator):
        itens = Item.objects.filter(categoria = categoria)
        if(itens):
            return objectsToStringForItens(itens, 'nome', separator)
        else:
            return "None"
    
    @soapmethod(soap_types.String, soap_types.String, _returns=soap_types.String)
    def mesasResponsavel(self, funcionario_id, separator):
        mesas = Mesa.objects.filter(garcom_responsavel = funcionario_id, em_aberto = True)
        if(mesas):
            return objectsToString(mesas, 'numero', separator, "Mesa ")
        else:
            return "None"
    
    @soapmethod(soap_types.String, soap_types.String, _returns=soap_types.Boolean)
    def registrarMesa(self, funcionario_id, num_mesa):
        num_mesa = int(num_mesa)
        try:
            Mesa.objects.get(numero = num_mesa, em_aberto = True)
        except:
            mesa = Mesa()
            mesa.numero = int(num_mesa)
            mesa.garcom_responsavel = Funcionario.objects.get(id=funcionario_id)
            mesa = mesa.save()
            return True
        return False

android_service = AndroidService()